package com.jfinalnat.httpclient.sdk;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.ContentType;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MyResponseHandler<T> implements ResponseHandler<T> {

	private Class<T> clazz;
	
	public MyResponseHandler(Class<T> clazz) {
		this.clazz = clazz;
	}

	/**
	 * JSON 响应处理
	 */
	public T handleResponse(HttpResponse response){
		
		Gson gson = null;
		Reader reader = null;
		HttpEntity entity = response.getEntity();
	    StatusLine statusLine = response.getStatusLine();
	    
	    try {
		    if (statusLine.getStatusCode() >= 300) {
					throw new HttpResponseException(
					        statusLine.getStatusCode(),
					        statusLine.getReasonPhrase());
		    }
		    if (entity == null) {
		        throw new ClientProtocolException("Response contains no content");
		    }
		    gson = new GsonBuilder().create();
		    
		    ContentType contentType = ContentType.getOrDefault(entity);
		    Charset charset = contentType.getCharset();
		    reader = new InputStreamReader(entity.getContent(), charset);
		    
	    } catch (HttpResponseException e) {
	    	e.printStackTrace();
	    } catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedOperationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	    
		return gson.fromJson(reader, clazz);
	}
}
